package com.yimi.yinhepda.views.setting_module;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;

import com.pda.ym.base.BaseActivity;
import com.pda.ym.base.BaseTitleActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.StringHelper;
import com.pda.ym.utils.SystemEnvironment;
import com.yimi.yinhepda.utils.spinner.SpinnerWithCodeAdapter;

import org.jetbrains.annotations.NotNull;

/**
 * 服务设置界面
 *
 * @author 000432
 */
public class ServerSettingActivity extends BaseTitleActivity {
    private Spinner serverSpinner;
    private SpinnerWithCodeAdapter serverAdapter;
    /**
     * 设置框中服务器IP的文本框
     */
    private EditText serverIP, et_updateapp_url;
    private String oldServerIp = "";
    /**
     * 卸车串货提示开关
     */
    private CheckBox mUnloadChuanHuo;
    /**
     * 错分强制确认
     */
    private CheckBox mCbForceOK;

    @Override
    public int setContentViewId() {
        return R.layout.activity_server_setting;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
        initEvent();
    }

    @Override
    public String getPageName() {
        return "服务地址设置";
    }

    public void initView() {
        serverSpinner = findViewById(R.id.serverIPSpinner);
        serverIP = findViewById(R.id.setting_serverIP);
        et_updateapp_url = findViewById(R.id.et_updateapp_url);
        //卸车串货提示开关
        mUnloadChuanHuo = findViewById(R.id.cb_unLoad_chuanhuo);
        mCbForceOK = findViewById(R.id.cb_wrongForceOK);
    }

    private void initData() {
        //初始化服务器数据列表(包含服务器名称和Ip地址)
        serverAdapter = new SpinnerWithCodeAdapter(this, SystemEnvironment.getStatusListForSpinner(false), serverSpinner);
        String currentIp = SharedPreferUtil.getInstance().getServerIp();
        //设置spinner选项
        serverAdapter.setSelectedOption(currentIp);
        et_updateapp_url.setText(SharedPreferUtil.getInstance().getServerIp());
        //设置默当前的服务地址
        serverIP.setText(SharedPreferUtil.getInstance().getServerIp());
        //初始化卸车串货提示开关
        if (sharedPreferUtil.getUnLoadChuanHuoSwitch()) {
            mUnloadChuanHuo.setChecked(true);
        } else {
            mUnloadChuanHuo.setChecked(false);
        }
        boolean isCheck = sharedPreferUtil.getBooleanValue(Common.LOAD_WRONG_FORCE_SURE);
        if (isCheck) {
            mCbForceOK.setChecked(true);
        } else {
            mCbForceOK.setChecked(false);
        }
    }

    private void initEvent() {
        findViewById(R.id.ok_btn).setOnClickListener(this);
        findViewById(R.id.back_btn).setOnClickListener(this);
        //根据监听改变地址
        serverSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String label = serverAdapter.getItem(position);
                String ip = SystemEnvironment.getStatusCodeByLabel(label);
                serverIP.setText(ip);
                et_updateapp_url.setText(ip);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //强制确认开关
        mCbForceOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout layout = (LinearLayout) LayoutInflater.from(ServerSettingActivity.this).inflate(R.layout.alert_dialog_load_wrong_force_ok, null);
                final EditText password = (EditText) layout.findViewById(R.id.load_wrong_force_password);
                Button sureButton = (Button) layout.findViewById(R.id.load_wrong_force_ok);
                Button cancleButton = (Button) layout.findViewById(R.id.load_wrong_force_cancle);
                final Dialog dialog = new Dialog(ServerSettingActivity.this, R.style.AsyncTaskDialog);
                dialog.addContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                dialog.getWindow().getDecorView().setPadding(10, 0, 10, 0);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setCancelable(false);
                dialog.show();

                sureButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String pwd = password.getText().toString();
                        if (!getString(R.string.load_wrong_force_pwd).equals(pwd)) {
                            //提示密码错误
                            showToast(getString(R.string.wrong_pwd));
                            return;
                        }
                        if (mCbForceOK.isChecked()) {
                            sharedPreferUtil.setBooleanValue(Common.LOAD_WRONG_FORCE_SURE, true);
                        } else {
                            sharedPreferUtil.setBooleanValue(Common.LOAD_WRONG_FORCE_SURE, false);
                        }
                        dialog.dismiss();
                    }
                });
                cancleButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean isCheck = sharedPreferUtil.getBooleanValue(Common.LOAD_WRONG_FORCE_SURE);
                        if (isCheck) {
                            mCbForceOK.setChecked(true);
                        } else {
                            mCbForceOK.setChecked(false);
                        }
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ok_btn:
                save();
                break;
            case R.id.back_btn:
                finish();
                break;
            default:
                break;
        }
    }

    private void save() {
        if (TextUtils.isEmpty(serverIP.getText().toString().trim())) {
            showToast("请输入服务器地址");
            return;
        }
        if (TextUtils.isEmpty(et_updateapp_url.getText().toString().trim())) {
            showToast("请输入更新服务器地址");
            return;
        }

        //设置服务器地址
        oldServerIp = Constants.getServerIp();
        String serverIPNew = serverIP.getText().toString().trim();
        if (!StringHelper.isEmpty(serverIPNew)) {
            if (serverIPNew.lastIndexOf("/") != serverIPNew.length() - 1) {
                serverIPNew = serverIPNew + "/";
            }
            //记录服务器地址
            SharedPreferUtil.getInstance().setServerIP(serverIPNew);
        }
        Constants.setNewLoad();
        //IP变更时发生的逻辑
        if (!oldServerIp.equals(serverIPNew)) {
            // 设置服务器ip已经改变，方便在mainActivity里面重新获取基础数据
            SharedPreferUtil.getInstance().setServerIpHaveChanged(true);
        }else{
            SharedPreferUtil.getInstance().setServerIpHaveChanged(false);
        }
        SharedPreferUtil.getInstance().setValue(Constants.UPDATE_SERVER, et_updateapp_url.getText().toString().trim());
        Constants.UPDATE_SERVER_URL = et_updateapp_url.getText().toString().trim();

        //保存卸车串货提示开关
        if (mUnloadChuanHuo.isChecked()) {
            sharedPreferUtil.setUnloadChuanhuoSwitch(true);
        } else {
            sharedPreferUtil.setUnloadChuanhuoSwitch(false);
        }

        showToast("保存成功");
        finish();
    }

    @Override
    public boolean showBack() {
        return false;
    }

    @Override
    public void setBack() {

    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
